package com.example.sudoku

import com.example.sudoku.SudokuService.Companion.seedArray
import org.springframework.stereotype.Service
import java.util.*

@Service
class SudokuService {

    companion object {
        val seedArray = arrayOf(intArrayOf(9, 7, 8, 3, 1, 2, 6, 4, 5), intArrayOf(3, 1, 2, 6, 4, 5, 9, 7, 8), intArrayOf(6, 4, 5, 9, 7, 8, 3, 1, 2), intArrayOf(7, 8, 9, 1, 2, 3, 4, 5, 6), intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9), intArrayOf(4, 5, 6, 7, 8, 9, 1, 2, 3), intArrayOf(8, 9, 7, 2, 3, 1, 5, 6, 4), intArrayOf(2, 3, 1, 5, 6, 4, 8, 9, 7), intArrayOf(5, 6, 4, 8, 9, 7, 2, 3, 1))
        fun getRandomNum(): Int {
            return (Math.random() * 9).toInt() + 1
        }
    }

    fun createNineRandomArray(): ArrayList<Int> {
        val list: ArrayList<Int> = arrayListOf()
        for (i in 0 until 9) {
            var randomNum = getRandomNum()
            while (true) {
                if (!list.contains(randomNum)) {
                    list.add(randomNum)
                    break
                }
                randomNum = getRandomNum()
            }
        }
        println("random array is --> $list")
        return list
    }

    fun createSudokuArray(randomList: ArrayList<Int>) :Array<IntArray> {
        val sudokuArray = Array(9) { IntArray(9) { 0 } }
        for (i in 0 until 9) {
            for (j in 0 until 9) {
                for (k in 0 until 9) {
                    if (seedArray[i][j] == randomList[k]) {
                        sudokuArray[i][j] = randomList[(k + 1) % 9]
                        break
                    }
                }
            }
        }
        printArray(sudokuArray)
        return sudokuArray
    }

    fun createSudokuQuestion(a: Array<IntArray>) : Array<IntArray> {
        val rand = Random()
        for (i in 0 until 9) {
            for (j in 0 until 7) {
                a[i][rand.nextInt(9)] = 0
            }
        }
        printArray(a)
        return a
    }

    fun printArray(a: Array<IntArray>) {
        for (i in 0 until 9) {
            for (j in 0 until 9) {
                print(" ${a[i][j]}")
                if ((j + 1) % 3 == 0) {
                    print(" ")
                }
            }
            println()
            if (0 == ((i + 1) % 3)) {
                println()
            }
        }
    }
}